package com.heima.stream;

import org.apache.kafka.streams.KeyValue;
import org.apache.kafka.streams.StreamsBuilder;
import org.apache.kafka.streams.kstream.*;
import org.springframework.context.annotation.Bean;

import java.time.Duration;
import java.util.Arrays;

//@Configuration
//@Slf4j
public class WordCountsDemo {

    /* 统计每个单词出现的次数 */
    @Bean
    public KStream<String, String> kStream(StreamsBuilder streamsBuilder) {
        //创建kstream对象，同时指定从那个topic中接收消息
        /* hello world */
        /* hello kafka */
        KStream<String, String> stream = streamsBuilder.stream("itcast-topic-input");
        /*stream.flatMapValues(new ValueMapper<String, Iterable<String>>() {
            @Override
            public Iterable<String> apply(String value) {
                // value === hello kafka
                return Arrays.asList(value.split(" "));
            }
        })
                //根据value进行聚合分组
                .groupBy((key, value) -> value)
                //聚合计算时间间隔   10
                .windowedBy(TimeWindows.of(Duration.ofSeconds(30)))
                //求单词的个数
                .count()
                .toStream()
                //处理后的结果转换为string字符串
                .map((key, value) -> {
                    System.out.println("key:" + key + ",value:" + value);
                    return new KeyValue<>(key.key().toString(), value.toString());
                })
                //发送消息
                .to("itcast-topic-out");*/
        stream.flatMapValues(new ValueMapper<String, Iterable<?>>() {
            @Override
            public Iterable<?> apply(String value) {
                System.out.println("flatMapValues: " + value);
                return Arrays.asList(value.split(" "));
            }
        }).groupBy(new KeyValueMapper<String, Object, Object>() {
            @Override
            public Object apply(String key, Object value) {
                // Key 值为空
                // Value值为上面集合中的每个元素
                // 返回value也就是根据value进行分组
                return value;
            }
        }).windowedBy(TimeWindows.of(Duration.ofSeconds(30)))
                .count()
                .toStream()
                .map(new KeyValueMapper<Windowed<Object>, Long, KeyValue<?, ?>>() {
                    @Override
                    public KeyValue<?, ?> apply(Windowed<Object> key, Long value) {
                        // key 统计的条目 也就是上面返回的Value
                        // value 统计的结果
                        return new KeyValue<>(key.key().toString(), value.toString());
                    }
                }).to("itcast-topic-out");
        return stream;
    }
}
